package com.dengyiming.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dengyiming.common.client.ItemClient;
import com.dengyiming.common.dto.Item;
import com.dengyiming.common.dto.PageDTO;
import com.dengyiming.item.service.IItemService;
import com.dengyiming.search.constants.MqConstants;
import com.dengyiming.search.pojo.ItemDoc;
import com.dengyiming.search.pojo.SearchDTO;
import com.dengyiming.search.service.SearchService;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.naming.directory.SearchResult;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private RestHighLevelClient client;
    @Autowired
    private ItemClient itemClient;
    @Override
    public PageDTO<ItemDoc> searchList(SearchDTO searchDTO) throws IOException {
        SearchRequest request = new SearchRequest("item");
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        String key = searchDTO.getKey();
        if (key == null || "".equals(key)) {
            boolQuery.must(QueryBuilders.matchAllQuery());
        } else {
            boolQuery.must(QueryBuilders.matchQuery("all", key));
        }
        if (searchDTO.getBrand() != null && !"".equals(searchDTO.getBrand())) {
            boolQuery.filter(QueryBuilders.termQuery("brand", searchDTO.getBrand()));
        }
        if (searchDTO.getCategory() != null && !"".equals(searchDTO.getCategory())) {
            boolQuery.filter(QueryBuilders.termQuery("category", searchDTO.getCategory()));
        }
        if (searchDTO.getMaxPrice() != null && searchDTO.getMinPrice() != null) {
            boolQuery.filter(QueryBuilders.rangeQuery("price")
                    .gte(searchDTO.getMinPrice() * 100)
                    .lte(searchDTO.getMaxPrice() * 100)
            );
        }
        if (!"default".equals(searchDTO.getSortBy())) {
            request.source().sort(searchDTO.getSortBy(), SortOrder.DESC);
        }
        request.source().query(boolQuery);
        request.source()
                .from((searchDTO.getPage() - 1) * searchDTO.getSize())
                .size(searchDTO.getSize());
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        long total = hits.getTotalHits().value;
        SearchHit[] hits1 = hits.getHits();
        List<ItemDoc> list = new ArrayList();
        for (SearchHit hit : hits1) {
            String hitJson = hit.getSourceAsString();
            ItemDoc itemDoc = JSON.parseObject(hitJson, ItemDoc.class);
            list.add(itemDoc);
        }

        return new PageDTO<ItemDoc>(total, list);

    }

    @Override
    public Map<String, List<String>> searchFilters(SearchDTO params) {
        try {
            // 1.准备Request
            SearchRequest request = new SearchRequest("item");
            // 2.准备DSL
            // 2.1.query
            BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
            String key = params.getKey();
            if (key == null || "".equals(key)) {
                boolQuery.must(QueryBuilders.matchAllQuery());
            } else {
                boolQuery.must(QueryBuilders.matchQuery("all", key));
            }
            if (params.getBrand() != null && !"".equals(params.getBrand())) {
                boolQuery.filter(QueryBuilders.termQuery("brand", params.getBrand()));
            }
            if (params.getCategory() != null && !"".equals(params.getCategory())) {
                boolQuery.filter(QueryBuilders.termQuery("category", params.getCategory()));
            }
            if (params.getMaxPrice() != null && params.getMinPrice() != null) {
                boolQuery.filter(QueryBuilders.rangeQuery("price")
                        .gte(params.getMinPrice() * 100)
                        .lte(params.getMaxPrice() * 100)
                );
            }
            if (!"default".equals(params.getSortBy())) {
                request.source().sort(params.getSortBy(), SortOrder.DESC);
            }
            request.source().query(boolQuery);
            // 2.2.设置size
            request.source().size(0);
            // 2.3.聚合
            buildAggregation(request);
            // 3.发出请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            // 4.解析结果
            Map<String, List<String>> result = new HashMap<>();
            Aggregations aggregations = response.getAggregations();
            // 4.1.根据品牌名称，获取品牌结果
            List<String> brandList = getAggByName(aggregations, "brandAgg");
            result.put("brand", brandList);
            // 4.2.根据品牌名称，获取品牌结果
            List<String> cityList = getAggByName(aggregations, "categoryAgg");
            result.put("category", cityList);
            // 4.3.根据品牌名称，获取品牌结果

            return result;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<String> searchSuggestion(String key) {
        try {
            // 1.准备Request
            SearchRequest request = new SearchRequest("item");
            // 2.准备DSL
            request.source().suggest(new SuggestBuilder().addSuggestion(
                    "suggestions",
                    SuggestBuilders.completionSuggestion("suggestion")
                            .prefix(key)
                            .skipDuplicates(true)
                            .size(10)
            ));
            // 3.发起请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            // 4.解析结果
            Suggest suggest = response.getSuggest();
            // 4.1.根据补全查询名称，获取补全结果
            CompletionSuggestion suggestions = suggest.getSuggestion("suggestions");
            // 4.2.获取options
            List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
            // 4.3.遍历
            List<String> list = new ArrayList<>(options.size());
            for (CompletionSuggestion.Entry.Option option : options) {
                String text = option.getText().toString();
                list.add(text);
            }
            return list;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void buildAggregation(SearchRequest request) {
        request.source().aggregation(AggregationBuilders
                .terms("brandAgg")
                .field("brand")
                .size(100)
        );
        request.source().aggregation(AggregationBuilders
                .terms("categoryAgg")
                .field("category")
                .size(100)
        );
        /*request.source().aggregation(AggregationBuilders
                .terms("starAgg")
                .field("starName")
                .size(100)
        );*/
    }

    private List<String> getAggByName(Aggregations aggregations, String aggName) {
        // 4.1.根据聚合名称获取聚合结果
        Terms brandTerms = aggregations.get(aggName);
        // 4.2.获取buckets
        List<? extends Terms.Bucket> buckets = brandTerms.getBuckets();
        // 4.3.遍历
        List<String> brandList = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            // 4.4.获取key
            String key = bucket.getKeyAsString();
            brandList.add(key);
        }
        return brandList;
    }
    @Override
    public void deleteById(Long id) {
        try {
            DeleteRequest request = new DeleteRequest("item", id.toString());
            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    @Override
    public void insertById(Long id) {
        try {

            Item item = itemClient.itemById(id);
            ItemDoc itemDoc = new ItemDoc(item);
            String itemJson = JSON.toJSONString(itemDoc);

            IndexRequest request = new IndexRequest("item").id(itemDoc.getId().toString());
            request.source(itemJson, XContentType.JSON);
            client.index(request,RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
